from shapely import Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon
import shapely.geometry as geometry
from pathlib import Path
from pandas import read_excel
from geopandas import GeoDataFrame
from typing import Literal


class ExcelToShp:
    def __init__(
            self,
            file_list: list,
            columns: list,
            x: str = None,
            y: str = None,
            z: str = None,
            m: str = None,
            _type: Literal['Point', 'MultiPoint', 'LineString', 'MultiLineString', 'Polygon', 'MultiPolygon'] = None
    ):
        self.file_list = file_list
        self.x = x
        self.y = y
        self.z = z
        self.m = m
        self._type = _type
        columns.append('geometry')
        self.gpd = GeoDataFrame(columns=columns, crs='EPSG:4532')

    def s(self):
        geom_list = []
        for index, file in enumerate(self.file_list):
            line = []
            pd = read_excel(file)
            if len(pd) == 0:
                continue
            for i in range(len(pd)):
                loc = pd.loc[i]
                xy = [loc[self.x], loc[self.y]]
                if self.z is not None:
                    xy.append([loc[self.m], loc[self.z]])
                line.append(xy)

            self.gpd.loc[index] = pd.loc[0]
            geom = getattr(geometry, self._type)(line)
            geom_list.append(geom)
        self.gpd['geometry'] = geom_list
        # print(type(self.gpd.loc[0]['速度(KM/H)']).__name__)
        # self.gpd['速度(KM/H)'] = [str(i) for i in self.gpd['速度(KM/H)']]
        for i in self.gpd:
            print(self.gpd[i].dtype)

    def save(self, path: str):
        self.gpd.to_file(path, driver='ESRI Shapefile', index=False, encoding='gbk')


if __name__ == '__main__':
    columns = list(read_excel(r'F:\PythonObject\office-tools\tools\shp\线路轨迹\35335信宜\去程 (1).xlsx').columns)
    file_list = list(Path(r'F:\PythonObject\office-tools\tools\shp\线路轨迹').glob('**/*.xlsx'))
    eshp = ExcelToShp(file_list=file_list, columns=columns, x='经度', y='纬度', _type='LineString')
    eshp.s()
    eshp.save(r'F:\PythonObject\office-tools\ww\test.shp')
